import pygame.image
from pygame import sprite

import baseItem
from bullet import Bullet


class Tank(baseItem.BaseItem):
    def __init__(self,tank_u,tank_d,tank_l,tank_r,left, top,speed=1):
        super().__init__()
        self.images = {
            "U": pygame.image.load(tank_u),
            "D": pygame.image.load(tank_d),
            "L": pygame.image.load(tank_l),
            "R": pygame.image.load(tank_r),
        }
        self.speed = 1,
        self.direction = "U"
        self.image = self.images[self.direction]
        # 坦克所在区域
        self.rect = self.image.get_rect()
        # 坦克初始化位置
        self.rect.left = left
        self.rect.top = top
        self.speed = speed
        self.stop = True
        self.live = True
        # 碰撞还原
        self.old_left = self.rect.left
        self.old_top = self.rect.top

    def move(self,screen_width,screen_height):
        #记录移动前的坐标
        self.old_left = self.rect.left
        self.old_top = self.rect.top

        if self.direction == "U":
            if self.rect.top > 0:
                self.rect.top -= self.speed
        if self.direction == "D":
            if self.rect.top < screen_height - self.rect.height:
                self.rect.top += self.speed
        if self.direction == "L":
            if self.rect.left > 0:
                self.rect.left -= self.speed
        if self.direction == "R":
            if self.rect.left < screen_width - self.rect.width:
                self.rect.left += self.speed
        pass

    def stay(self):
        self.rect.left = self.old_left
        self.rect.top = self.old_top

    def hit(self,tank_list):
        for tank in tank_list:
            if self != tank:
                if sprite.collide_rect(self, tank):
                    self.stay()

    def shot(self):
        return Bullet(self)

    # 展示tank（surface）
    def display(self,window):
        # 1.重新加载tank图片
        self.image = self.images[self.direction]
        # 2.将tank加载到窗口中
        window.blit(self.image, self.rect)
        pass
